﻿/* NOTIFY */
function Notify() { }
Notify.prototype.alert = function (msg, header) {
    var _header = header || '';
    $.jGrowl(msg, { header: "Alert: " + _header, css: 'ui-state-error', sticky: true });
};
Notify.prototype.info = function (msg, header) {
    var _header = header || '';
    $.jGrowl(msg, { header: "Info: " + _header });
};

/* DATATABLES HELPER FUNCTIONS */
function DataTableAdapter(service, tableID, options) {
    var config = {};
    $.extend(config, options);
    config.sort = ('sort' in config) ? config.sort : [[1, 'asc']];
    config.hasAdd = ('add' in service);
    config.hasDrill = ('drill' in service);
    config.hasEdit = ('edit' in service);
    config.hasLink = ('link' in service);
    config.hasLoad = ('load' in service);
    config.hasPut = ('put' in service);
    config.hasOpenPut = ('openput' in service);
    config.hasRemove = ('remove' in service);
    config.hasSave = ('save' in service);
    var registry = {};
    registry.table = this.fillTable(tableID, config);
    registry.service = service;

    if (config.hasAdd)
        window.PageBus.subscribe('table.add.' + tableID, this, this.addHandler, registry);
    if (config.hasDrill)
        window.PageBus.subscribe('table.drill.' + tableID, this, this.drillHandler, registry);
    if (config.hasEdit)
        window.PageBus.subscribe('table.edit.' + tableID, this, this.editHandler, registry);
    if (config.hasLink)
        window.PageBus.subscribe('table.link.' + tableID, this, this.linkHandler, registry);
    if (config.hasLoad)
        window.PageBus.subscribe('table.load.' + tableID, this, this.loadHandler, registry);
    if (config.hasPut)
        window.PageBus.subscribe('table.put.' + tableID, this, this.putHandler, registry);
    if (config.hasOpenPut)
        window.PageBus.subscribe('table.openput.' + tableID, this, this.openPutHandler, registry);
    if (config.hasRemove)
        window.PageBus.subscribe('table.remove.' + tableID, this, this.removeHandler, registry);
    if (config.hasSave)
        window.PageBus.subscribe('table.save.' + tableID, this, this.saveHandler, registry);
}
DataTableAdapter.prototype.fillTable = function (tableID, config) {
    var oTable = $("#" + tableID).dataTable({
        sPaginationType: "full_numbers",
        bStateSave: true,
        bFilter: true,
        bLengthChange: true,
        aaSorting: config.sort,
        fnDrawCallback: function () {
            iconify();
        },
        fnInitComplete: function () {
        },
        aoColumnDefs: [
			        {
			            fnRender: function (oObj) {
			                var id = oObj.aData[0];
			                var text = '';
			                if (config.hasEdit)
			                    text += toButton("table.edit." + tableID, id, "edit", "Edit");
			                if (config.hasLink)
			                    text += toButton("table.link." + tableID, id, "link", "Link");
			                if (config.hasOpenPut)
			                    text += toButton("table.openput." + tableID, id, "load", "Open Load");
			                if (config.hasDrill)
			                    text += toButton("table.drill." + tableID, id, "drill", "Drilldown");
			                if (config.hasRemove)
			                    text += toButton("table.remove." + tableID, id, "delete", "Remove");
			                return text;
			            },
			            aTargets: [0],
			            sClass: "ItemID"
			        }
		        ]
    });
    return oTable;
};
DataTableAdapter.prototype.addHandler = function (subj, obj, registry) {
    function updateTable(result) {
        var success = ((result.Values) && result.Values.length > 0);
        if (success) {
            registry.table.fnAddData(result.Values);
        }
        window.PageBus.publish(subj + '.done', success, result.Message);
    }
    registry.service.add(obj, updateTable);
};
DataTableAdapter.prototype.drillHandler = function (subj, rowButton, registry) {
    var values = this.getRowValues(rowButton);
    registry.service.drill(values);
};
DataTableAdapter.prototype.editHandler = function (subj, rowButton, registry) {
    var values = this.getRowValues(rowButton);
    var row = rowButton.parentNode.parentNode;
    this.editIndex = registry.table.fnGetPosition(row);
    registry.service.edit(values);
    iconify();
    $(registry.table.fnSettings().aoData).each(function () {
        $(this.nTr).removeClass('row_selected');
    });
    $(row).addClass('row_selected');
    //TODO: mark row as edited
};
DataTableAdapter.prototype.linkHandler = function (subj, rowButton, registry) {
    var values = this.getRowValues(rowButton);
    registry.service.link(values);
};
DataTableAdapter.prototype.loadHandler = function (subj, rowButton, registry) {
    var values = this.getRowValues(rowButton);
    registry.service.load(values);
};
DataTableAdapter.prototype.putHandler = function (subj, obj, registry) {
    var index = this.editIndex;
    function updateTable(result) {
        var success = result.Values && result.Values.length > 0;
        if (success)
            registry.table.fnUpdate(result.Values, index);
        window.PageBus.publish(subj + '.done', success, result.Message);
    }
    registry.service.put(obj, updateTable);
};
DataTableAdapter.prototype.openPutHandler = function (subj, rowButton, registry) {
    var values = this.getRowValues(rowButton);
    this.editIndex = registry.table.fnGetPosition(rowButton.parentNode.parentNode);
    registry.service.openput(values);
    iconify();
};
DataTableAdapter.prototype.removeHandler = function (subj, rowButton, registry) {
    if (!confirm("Delete this record?")) {
        return;
    }
    var values = this.getRowValues(rowButton);
    var row = $(rowButton).parent().parent();
    function removeRow(result) {
        if (result.Message == "Success")
            row.remove();
        else
            alert("There was a problem removing this record");
    }
    registry.service.remove(values, removeRow);
};
DataTableAdapter.prototype.saveHandler = function (subj, obj, registry) {
    var index = this.editIndex;
    function updateTable(result) {
        var success = result.Values && result.Values.length > 0;
        if (success) {
            registry.table.fnUpdate(result.Values, index, null, false);
            iconify();
        }
        window.PageBus.publish(subj + '.done', success, result.Message);
    }
    registry.service.save(obj, updateTable);
};
DataTableAdapter.prototype.getRowValues = function (button) {
    var $button = $(button);
    var values = [];
    values.push($button.val());
    var row = $button.parent().parent();
    row.children("td").each(function (index) {
        switch (index) {
            case 0:
                break;
            default:
                values.push($(this).text());
        }
    });
    return values;
};

function DomainService(dialogID, tableID) {
    var _dialog = $('#' + dialogID);
    _dialog.dialog({
        autoOpen: false,
        height: 350,
        width: 500,
        modal: true,
        title: 'Domain Details',
        buttons: {
            'Save': function () {
                var obj = {};
                obj.ID = $('#RecordID').val();
                obj.Name = $('#DomainName').val();
                obj.Ideology = $('#IdeologyType').val();
                obj.Media = $('#MediaType').val();
                obj.Organization = $('#OrganizationType').val();
                obj.Party = $('#PartyType').val();
                obj.Social = $('#SocialType').val();
                obj.Theme = $('#ThemeType').val();
                window.PageBus.publish('table.save.' + tableID, obj);
            },
            'Close': function () {
                _dialog.dialog("close");
            }
        }
    });
    this.dialog = _dialog;
}
DomainService.prototype.dialog = null;
DomainService.prototype.edit = function (values) {
    $('#RecordID').val(values[0]);
    $('#DomainName').val(values[1]);
    $('#IdeologyType').val(values[2]);
    $('#MediaType').val(values[3]);
    $('#OrganizationType').val(values[4]);
    $('#PartyType').val(values[5]);
    $('#SocialType').val(values[6]);
    $('#ThemeType').val(values[7]);
    this.dialog.dialog("open");
};
DomainService.prototype.link = function (values) {
    window.open('http://' + values[1], 'newwindow');
};
DomainService.prototype.save = function (obj, callback) {
    var _dialog = this.dialog;
    function myCallback(result) {
        _dialog.dialog("close");
        callback(result);
    }
    var _data = JSON.stringify(obj);
    $.ajax({ type: 'POST', url: "/Domain/Save", data: _data, success: myCallback, dataType: "json", contentType: "application/json; charset=utf-8", traditional: true });
};


function toCheckMark(id, name, value, label) {
    var text = '<input type="checkbox" id="' + id + '" name="' + name + '" value="' + value + '"  />';
    if (label) {
        text += '<label for="' + id + '">' + label + '</label>';
    }
    return text;
}
function toButton(subject, value, aClass, label) {
    var _class = (aClass) ? aClass : '';
    var _label = (label) ? label : '';
    var _value = (value) ? value : '';
    return "<button class='" + _class + "' value='" + _value + "' onclick='window.PageBus.publish(\"" + subject + "\", this)' >" + _label + "</button>";
}



function Service() { }
Service.post = function (url, data, callback, dataType) {
    var _data = JSON.stringify(data);
    var _dataType = (dataType == null) ? "json" : dataType;
    $.ajax({ type: 'POST', url: url, data: _data, success: callback, error: errorHandler, dataType: _dataType, contentType: "application/json; charset=utf-8" });
};
Service.postJson = function (url, data, callback, dataType) {
    var _data = JSON.stringify(data);
    var _dataType = (dataType == null) ? "json" : dataType;
    $.ajax({ type: 'POST', url: url, data: _data, success: callback, error: errorHandler, dataType: _dataType, contentType: "application/json; charset=utf-8", traditional: true });
};
Service.get = function (url, data, callback, dataType) {
    var _dataType = (dataType == null) ? "json" : dataType;
    $.ajax({ url: url, data: data, success: callback, error: errorHandler, dataType: _dataType });
};



function Add(elem, meth, callback) { this.element = elem; this.method = meth; this.callback = callback; }
Add.prototype.element = null;
Add.prototype.method = null;
Add.prototype.callback = null;


/* ENUMS */

function AffectiveFrame() { }
AffectiveFrame.Positive = "Positive";
AffectiveFrame.Negative = "Negative";
AffectiveFrame.Neutral = "Neutral";

function Status() { }
Status.Undefined = "Undefined";
Status.Unknown = "Unknown";
Status.Active = "Active";
Status.Inactive = "Inactive";
Status.Pending = "Pending";
Status.Complete = "Complete";
Status.Rejected = "Rejected";
Status.Development = "Development";
Status.New = "New";

function encode_utf8(s) {
    return unescape(encodeURIComponent(s));
}

function decode_utf8(s) {
    return decodeURIComponent(escape(s));
}
function iconify() {
    $(".open").button({ icons: { primary: 'ui-icon-folder-open' }, text: false });
    $(".drill").button({ icons: { primary: 'ui-icon-folder-open' }, text: false });
    $(".edit").button({ icons: { primary: 'ui-icon-pencil' }, text: false });
    $(".delete").button({ icons: { primary: 'ui-icon-trash' }, text: false });
    $(".remove").button({ icons: { primary: 'ui-icon-trash' }, text: false });
    $(".link").button({ icons: { primary: 'ui-icon-extlink' }, text: false });
    $(".load").button({ icons: { primary: 'ui-icon-transferthick-e-w' }, text: false });
    $(".openput").button({ icons: { primary: 'ui-icon-transferthick-e-w' }, text: false });
    $(".add").button({ icons: { primary: 'ui-icon-plusthick' }, text: false });
    $(":checkbox.button").button();
    $(".yesno").buttonset();
    $(":radio.button").button();
}

/* JQUERY FUNCTIONS */

function errorHandler(xhr, ajaxOptions, thrownError) {
    notify.alert(xhr.getResponseHeader('MerazHeader'));
}